/* © 2009 ROBO Design
 * http://www.robodesign.ro
 */

// Keep everything in anonymous function, called on window load.
if(window.addEventListener) {
    window.addEventListener('load', function () {
        var canvas, context, canvaso, contexto, couleur, epaisseur;

        // The active tool instance.
        var tool;
        var tool_default = 'line';

        function init () {
            // Find the canvas element.
            couleur = document.getElementById('couleur');
            canvaso = document.getElementById('imageView');
            epaisseur = document.getElementById('epaisseur');
            if (!canvaso) {
                alert('Error: I cannot find the canvas element!');
                return;
            }

            if (!canvaso.getContext) {
                alert('Error: no canvas.getContext!');
                return;
            }

            // Get the 2D canvas context.
            contexto = canvaso.getContext('2d');
            if (!contexto) {
                alert('Error: failed to getContext!');
                return;
            }

            // Add the temporary canvas.
            var container = canvaso.parentNode;
            canvas = document.createElement('canvas');
            if (!canvas) {
                alert('Error: I cannot create a new canvas element!');
                return;
            }

            canvas.id     = 'imageTemp';
            canvas.width  = canvaso.width;
            canvas.height = canvaso.height;
            container.appendChild(canvas);

            context = canvas.getContext('2d');

           

            // Activate the default tool.
            if (tools[tool_default]) {
                tool = new tools[tool_default]();                
            }

            // Attach the mousedown, mousemove and mouseup event listeners.
            canvas.addEventListener('mousedown', ev_canvas, false);
            canvas.addEventListener('mousemove', ev_canvas, false);
            canvas.addEventListener('mouseup',   ev_canvas, false);
            
                       
        }
        
        // The general-purpose event handler. This function just determines the mouse
        // position relative to the canvas element.
        function ev_canvas (ev) {
            if (ev.layerX || ev.layerX == 0) { // Firefox
                ev._x = ev.layerX;
                ev._y = ev.layerY;
            } else if (ev.offsetX || ev.offsetX == 0) { // Opera
                ev._x = ev.offsetX;
                ev._y = ev.offsetY;
            }

            // Call the event handler of the tool.
            var func = tool[ev.type];
            if (func) {
                func(ev);
            }
        }

        // The event handler for any changes made to the tool selector.
        function ev_tool_change (ev) {
            if (tools[this.value]) {
                tool = new tools[this.value]();
            }
        }
        
        
        var rectangle = document.getElementById("rectangle"); 
        rectangle.addEventListener('click', ev_tool_change, false);
        var cercle = document.getElementById("cercle"); 
        cercle.addEventListener('click', ev_tool_change, false);
        var pinceaux = document.getElementById("pinceaux"); 
        pinceaux.addEventListener('click', ev_tool_change, false);
        var ligne = document.getElementById("ligne"); 
        ligne.addEventListener('click', ev_tool_change, false);
        var gomme = document.getElementById("gomme"); 
        gomme.addEventListener('click', ev_tool_change, false);
        var reset = document.getElementById("reset"); 
        reset.addEventListener('click', resetB, false);
        
        //On récupère les id des boutons pour ensuite les traiter dans la fonction setCadre
        var img = document.getElementById("cadre1"); 
        img.addEventListener('click', setCadre, false);
        var img2 = document.getElementById("cadre2"); 
        img2.addEventListener('click', setCadre, false);
        var img3 = document.getElementById("cadre3"); 
        img3.addEventListener('click', setCadre, false);

        // This function draws the #imageTemp canvas on top of #imageView, after which
        // #imageTemp is cleared. This function is called each time when the user
        // completes a drawing operation.
        //        
           function setCadre(){
            if(this.id=="cadre1"){                        
                imageObj.src = "img/cadre1.png";
            }
            else if (this.id=="cadre2"){
                imageObj.src = "img/cadre2.png";
            } 
            else  if(this.id=="cadre3"){
                imageObj.src = "img/cadre3.png";
            }      
        
        }
       
       
        function img_update () {
            contexto.drawImage(canvas, 0, 0);
            context.clearRect(0, 0, canvas.width, canvas.height);
        }

        // This object holds the implementation of each drawing tool.
           
        var tools = {};
        
        // outil gomme
        tools.gomme = function () {
            var tool = this;
            this.started = false;
            var ancienX;
            var ancienY;

            // This is called when you start holding down the mouse button.
            // This starts the pencil drawing.
            this.mousedown = function (ev) {
                context.beginPath();
                context.moveTo(ev._x, ev._y);
                ancienX = ev._x;
                ancienY = ev._y;
                context.strokeStyle = '#FFF';
                context.lineWidth = epaisseur.value;
                tool.started = true;
            };

            
            this.mousemove = function (ev) {
                if (tool.started) {
                    context.lineTo(ev._x, ev._y);
                    context.stroke();

                    var objJSON = {
                        "type" : 'gomme', 
                        "x0" : ancienX, 
                        "y0" : ancienY, 
                        "x1" : ev._x, 
                        "y1" : ev._y,
                        "width" : context.lineWidth,
                        "color" : context.strokeStyle
                    };

                    // On envoie la figure sur tous les clients
                    now.distributeMessageDessin(objJSON);
                    
                    ancienX = objJSON.x1;
                    ancienY = objJSON.y1;

                }
            };

           
            this.mouseup = function (ev) {
                if (tool.started) {
                    tool.mousemove(ev);
                    tool.started = false;
                    img_update();		   
                   
                }
            };
        };
        
        

        // The drawing pencil.
        tools.pencil = function () {
            var tool = this;
            this.started = false;
            var ancienX;
            var ancienY;

            // This is called when you start holding down the mouse button.
            // This starts the pencil drawing.
            this.mousedown = function (ev) {

                context.beginPath();
                context.moveTo(ev._x, ev._y);
                ancienX = ev._x;
                ancienY = ev._y;
                context.strokeStyle = couleur.value;
                context.lineWidth = epaisseur.value;
                tool.started = true;
            };

            // This function is called every time you move the mouse. Obviously, it only
            // draws if the tool.started state is set to true (when you are holding down
            // the mouse button).
            this.mousemove = function (ev) {
                if (tool.started) {

                    context.lineTo(ev._x, ev._y);
                    context.stroke();

                    var objJSON = {
                        "type" : 'pencil', 
                        "x0" : ancienX, 
                        "y0" : ancienY, 
                        "x1" : ev._x, 
                        "y1" : ev._y,
                        "width" : context.lineWidth,
                        "color" : context.strokeStyle
                    };

                    // On envoie la figure sur tous les clients
                    now.distributeMessageDessin(objJSON);
                    
                    ancienX = objJSON.x1;
                    ancienY = objJSON.y1;

                }
            };

            // This is called when you release the mouse button.
            this.mouseup = function (ev) {
                if (tool.started) {
                    tool.mousemove(ev);
                    tool.started = false;
                    now.distributeMessageNotification("<span style=\"color:#888888 ;\"><i> Notification : " + this.now.name +" vient de dessiner à main levé.</i></span>");
                    img_update();
                }
            };
        };

        // The rectangle tool.
        tools.rect = function () {
            var tool = this;
            this.started = false;

            this.mousedown = function (ev) {
                tool.started = true;
                tool.x0 = ev._x;
                tool.y0 = ev._y;
            };

            this.mousemove = function (ev) {
                if (!tool.started) {
                    return;
                }

                x = Math.min(ev._x,  tool.x0),
                y = Math.min(ev._y,  tool.y0),
                w = Math.abs(ev._x - tool.x0),
                h = Math.abs(ev._y - tool.y0);

                context.clearRect(0, 0, canvas.width, canvas.height);

                if (!w || !h) {
                    return;
                }
                context.lineWidth = epaisseur.value;
                context.strokeStyle = couleur.value;
                context.strokeRect(x, y, w, h);
	  
            };

            this.mouseup = function (ev) {
                if (tool.started) {
                    tool.mousemove(ev);
                    tool.started = false;
                    img_update();
			
                    //On notifie
                    now.distributeMessageNotification("<span style=\"color:#888888 ;\"><i> Notification : " + this.now.name +" vient de dessiner un rectangle.</i></span>");
			
                    var objJSON = {
                        "type" : 'rectangle', 
                        "x" : x, 
                        "y" : y, 
                        "w" : w, 
                        "h" : h,
                        "width" : context.lineWidth,
                        "color" : context.strokeStyle
                    };

                    // On envoie la figure sur tous les clients
                    now.distributeMessageDessin(objJSON);
                
		
                }
            };
        };

        // Création d'une ligne
        tools.line = function () {
            var tool = this;
            this.started = false;

            this.mousedown = function (ev) {
                tool.started = true;
                tool.x0 = ev._x;
                tool.y0 = ev._y;
            };

            this.mousemove = function (ev) {
                if (!tool.started) {
                    return;
                }
                context.clearRect(0, 0, canvas.width, canvas.height);
                context.beginPath();
                context.moveTo(tool.x0, tool.y0);
                context.lineTo(ev._x,   ev._y);
                context.lineWidth = epaisseur.value;
                context.strokeStyle = couleur.value;
                context.stroke();
                context.lineCap='round';
                context.closePath();
            };

            this.mouseup = function (ev) {
                if (tool.started) {
                    tool.mousemove(ev);
                    tool.started = false;
                    
                    var objJSON = {
                        "type" : 'line', 
                        "x0" : tool.x0, 
                        "y0" : tool.y0, 
                        "x1" : ev._x, 
                        "y1" : ev._y,
                        "width" : context.lineWidth,
                        "color" : context.strokeStyle
                    };

                    //On notifie	
                    now.distributeMessageNotification("<span style=\"color:#888888 ;\"><i> Notification : " + this.now.name +" vient de dessiner une droite.</i></span>");
			

                    // On envoie la figure sur tous les clients
                    now.distributeMessageDessin(objJSON);

                    img_update();
                    
                }
            };
        };


        // cr�ation d'un cercle
        tools.circle = function () {
            var tool = this;
            this.started = false;

            this.mousedown = function (ev) {
                tool.started = true;
                tool.x0 = ev._x;
                tool.y0 = ev._y;
            };

            this.mousemove = function (ev) {
                if (!tool.started) {
                    return;
                }

                var x = Math.min(ev._x,  tool.x0),
                y = Math.min(ev._y,  tool.y0),
                w = Math.abs(ev._x - tool.x0),
                h = Math.abs(ev._y - tool.y0);
                u= Math.sqrt(w*w+h*h);

                context.clearRect(0, 0, canvas.width, canvas.height);
                context.beginPath();
                context.arc(tool.x0, tool.y0, u, 0, Math.PI*2, true);
                context.lineWidth = epaisseur.value;
                context.strokeStyle = couleur.value;
                context.closePath();
                context.stroke();


                if (!w || !h) {
                    return;
                }

            };

            this.mouseup = function (ev) {
                if (tool.started) {
                    tool.mousemove(ev);
                    tool.started = false;		
                    img_update();

                    var m = {};
                    m.type = 'cercle';
                    m.x0=tool.x0;
                    m.y0=tool.y0;
                    m.u=u;
                    m.width = context.lineWidth;
                    m.color = context.strokeStyle;
                    
                    //On notifie
                    now.distributeMessageNotification("<span style=\"color:#888888 ;\"><i> Notification : " + this.now.name +" vient de dessiner un cercle.</i></span>");
			
                    var objJSON = {
                        "type" : 'cercle', 
                        "x0" : tool.x0, 
                        "y0" : tool.y0, 
                        "u" : u,
                        "width" : context.lineWidth,
                        "color" : context.strokeStyle
                    };
            
                    // On envoie la figure sur tous les clients
                    now.distributeMessageDessin(objJSON);
			
                };
            };

        }
        function resetB(){           
            contexto.fillStyle = '#fff';
            contexto.fillRect(0, 0, canvaso.width, canvaso.height);
            var objJSON = {
                "type" : 'reset'
            };
            now.distributeMessageDessin(objJSON);            
        }
        
        init();

    }, false);
}



//CLIENT
//Méthodes permettant de récupérer le message crée dans les fonction du dessus, et de les envoyer au client

function envoieMessageText(){
    now.distributeMessage($("#text-input").val());
    $("#text-input").val("");
}

function envoieMessageDessin(message){
    now.distributeMessage(message);   
}

function img_update () {
    var canvas = document.getElementById('imageTemp');
    var context = canvas.getContext('2d');
    var canvaso = document.getElementById('imageView');
    var contexto = canvaso.getContext('2d');
    contexto.drawImage(canvas, 0, 0);
    context.clearRect(0, 0, canvas.width, canvas.height);
}


function dessinerRectangle(x,y,w,h,width,color){
    var canvas = document.getElementById('imageTemp');
    var context = canvas.getContext('2d');
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.lineWidth = width;
    context.strokeStyle = color;
    context.strokeRect(x, y, w, h);
    img_update();
}
function dessinerLigne(x0,y0,x1,y1,width,color){
    var canvas = document.getElementById('imageTemp');
    var context = canvas.getContext('2d');
    context.clearRect(0, 0, canvas.width, canvas.height);

    context.beginPath();
    context.moveTo(x0,y0);
    context.lineTo(x1,y1);
    context.lineWidth = width;
    context.strokeStyle = color;
    context.stroke();
    context.lineCap='round';
    context.closePath();
    img_update();
}
function dessinerCercle(xo,y0,u,width,color){
    var canvas = document.getElementById('imageTemp');
    var context = canvas.getContext('2d');

    context.clearRect(0, 0, canvas.width, canvas.height);
    context.beginPath();
    context.arc(xo, y0, u, 0,Math.PI*2, true);
    context.lineWidth = width;
    context.strokeStyle = color;
    context.closePath();
    context.stroke();
    img_update();
    
}
    
//$("#reset").click(function()  {  
function reset(){
    
    var canvaso = document.getElementById('imageView');
    var contexto = canvaso.getContext('2d');
    var canvas = document.createElement('canvas');   
    contexto.fillStyle = '#fff';
    contexto.fillRect(0, 0, canvaso.width, canvaso.height);    
    
}

// Bouton Save :
$("#save").click(function() {
    var canvas_tmp = document.getElementById("imageView");
    window.location = canvas_tmp.toDataURL("image/png");
});


//////////////
//
//
////////////////////chat code//////////////////

$(document).ready(function(){

    // Lorsqu'on reçoit un message on execute cette fonction
    now.receiveMessage = function(name, message){
        $("#messages").append(name + " : " + message + "<br>");
        //remonter le scrollbar pour le chat
        document.getElementById('messages').scrollTop = document.getElementById('messages').scrollHeight;
           
    }

    now.receiveMessageNotification = function(message){
        $("#messages").append(message + "<br>");
        //remonter le scrollbar pour le chat
        document.getElementById('messages').scrollTop = document.getElementById('messages').scrollHeight;
           
    }

    //Reception des message par le client, permet la fonctionnalité de multiparticipation
    now.receiveMessageDessin = function(obj){ 
        if(obj.type=='reset'){
            reset();
        }
      
        if(obj.type=='cercle'){
            x0=obj.x0;
            y0=obj.y0;
            u=obj.u;
            width=obj.width;
            color=obj.color;
            dessinerCercle(x0,y0,u,width,color);
        }
        if(obj.type=='line' || obj.type=='pencil' || obj.type=='gomme' ){
            x0 = obj.x0;
            y0 = obj.y0;
            x1 = obj.x1;
            y1 = obj.y1;
            width =obj.width;
            color=obj.color;
            dessinerLigne(x0,y0,x1,y1,width,color);
        }
        if(obj.type=='rectangle'){
            x = obj.x;
            y = obj.y;
            w = obj.w;
            h = obj.h;
            width =obj.width;
            color=obj.color;
            dessinerRectangle(x,y,w,h,width,color);
        }
        if(obj.type=='trait'){
            x0 = obj.x0;
            y0 = obj.y0;

            width =obj.width;
            color=obj.color;
            dessinerTrait(x0,y0,width,color);
        }	
    }
        
  
    // Quand on clique sur le bouton send, on exécute cette fonction
    $("#send-button").click(function(){
        now.distributeMessage($("#text-input").val());
        $("#text-input").val("");
        document.getElementById('messages').scrollTop = document.getElementById('messages').scrollHeight;b
    });

    // Poppe une fênêtre de dialogue et demande le nom
    now.name = prompt("What's your name?", "");
	

});
